package ee.ttu.agent.smartHouse.services;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import ee.ttu.agent.smartHouse.util.CustomACLMessage;

public class CustomLoggingBehaviour extends CyclicBehaviour {

	private static final long serialVersionUID = -1186101849519678442L;

	@Override
	public void action() {
		// TODO: investigate message template mechanism
		MessageTemplate mt = MessageTemplate
				.MatchPerformative(CustomACLMessage.GATEKEEPER_LOG1);
		ACLMessage msg = myAgent.blockingReceive(mt);
		if (msg != null) {
			String messageContent = msg.getContent();
			saveAccessLog(messageContent);
		} else {
			block();
		}
	}
	
	private void saveAccessLog(String logContent){
			try
		{
			String workingDir = System.getProperty("user.dir");
			String filename= "AccessLogPrimer.log";
		    String filePath = workingDir + File.pathSeparator + filename;
			
			FileWriter fw = new FileWriter(filePath,true); //append the new data
		    fw.write(logContent + System.getProperty("line.separator"));
		    fw.close();
		}
		catch(IOException ioe)
		{
		    System.err.println("IOException: " + ioe.getMessage());
		}
	}
	
}